""" -*- coding: utf-8 -*-"""
import re
from datetime import datetime
from models import db, Department, Project, Code


def generate_project_number(department_id, selected_code):
    """生成项目编号：年份 + 部门编号 + 序号"""
    current_year = datetime.now().strftime("%Y")

    # 查找该部门使用该编号的最大序号
    pattern = re.compile(rf"^{current_year}{re.escape(selected_code)}(\d{{3}})$")
    max_sequence = 0

    department = Department.query.get(department_id)
    if not department:
        return None

    for project in department.projects:
        match = pattern.match(project.project_number)
        if match:
            sequence_num = int(match.group(1))
            if sequence_num > max_sequence:
                max_sequence = sequence_num

    new_sequence = max_sequence + 1
    return f"{current_year}{selected_code}{new_sequence:03d}"


def get_or_create_code(code_value):
    """获取或创建编号对象"""
    code = Code.query.filter_by(value=code_value).first()
    if not code:
        code = Code(value=code_value)
        db.session.add(code)
        db.session.commit()
    return code